package _interview75;

import _object.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 199. 二叉树的右视图
 */
public class No199 {
    private List<Integer> ans;
    private int maxDeep;

    /**
     * 1. 深度优先遍历
     */
    public List<Integer> rightSideView1(TreeNode root) {
        ans = new ArrayList<>();
        dfs(root, 0);
        return ans;
    }

    private void dfs(TreeNode node, int deep) {
        if (node == null) return;
        if (deep == maxDeep) ans.add(node.val);
        maxDeep = Math.max(deep + 1, maxDeep);
        dfs(node.right, deep + 1);
        dfs(node.left, deep + 1);
    }

    /**
     * 2. 广度优先遍历
     */
    public List<Integer> rightSideView2(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null) return ans;

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            List<Integer> curList = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                curList.clear();
                TreeNode poll = queue.poll();
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
                curList.add(poll.val);
            }
            ans.add(curList.get(curList.size() - 1));
        }
        return ans;
    }
}
